"""
CRUD操作（增删改查）
C ---> Create ---> 增
D ---> Delete ---> 删
U ---> Update ---> 改
R --->  Read  ---> 查
"""
import MySQLdb
from MySQLdb.cursors import DictCursor


class Dept:

    def __init__(self, no, name, location):
        self.no = no
        self.name = name
        self.location = location

    def __str__(self):
        return f'{self.no}: {self.name}'


name = input('关键字: ')

conn = MySQLdb.connect(host='47.104.31.138', port=3306,
                       database='hrs', charset='utf8',
                       user='luohao', password='Luohao.618')
try:
    with conn.cursor(cursorclass=DictCursor) as cursor:
        cursor.execute(
            'select dno as no, dname as name, dloc as location from tb_dept '
            ' where dname like %s',
            (f'%{name}%', )
        )
        for row_dict in cursor.fetchall():
            dept = Dept(**row_dict)
            print(dept)
        # 通过cursor对象抓取查询结果，共有三个抓取数据的方法
        # fetchone() / fetchmany(n) / fetchall()
        # print(cursor.fetchall())
        # print('-' * 50)
        # print(cursor.fetchone())
        # print(cursor.fetchone())
        # print('-' * 50)
        # print(cursor.fetchmany(2))
except MySQLdb.MySQLError as err:
    print(err)
finally:
    conn.close()
